package com.zh.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.util.HtmlUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 消息链接/图片转换工具类
 */
public class MessageConvertUtil {

    // URL匹配正则（支持http/https/ftp）
    private static final Pattern URL_PATTERN = Pattern.compile(
            "(https?|ftp)://[^\\s/$.?#].[^\\s]*",
            Pattern.CASE_INSENSITIVE
    );

    // 图片链接匹配正则（常见图片格式）
    private static final Pattern IMAGE_PATTERN = Pattern.compile(
            "(https?://[^\\s]+(?:\\.(?:jpg|jpeg|png|gif|bmp|webp)))(?:\\?[^\\s]*)?",
            Pattern.CASE_INSENSITIVE
    );

    /**
     * 消息转化
     * @param content
     * @return
     */
    public static String parseTo(String content) {
        if (StringUtils.isBlank(content)) return content;
        // 转义HTML标签
        content = HtmlUtils.htmlEscape(content);
        // 转换URL为可点击链接
        content = convertUrlsToLinks(content);
        // 转换图片链接为缩略图标签
        content = convertImagesToThumbnails(content);
        return content;
    }

    /**
     * 提取消息中的所有URL
     */
    public static List<String> extractUrls(String content) {
        List<String> urls = new ArrayList<>();
        if (StringUtils.isBlank(content)) return urls;

        Matcher matcher = URL_PATTERN.matcher(content);
        while (matcher.find()) {
            urls.add(matcher.group());
        }
        return urls;
    }

    /**
     * 转换消息中的URL为可点击链接
     */
    public static String convertUrlsToLinks(String content) {
        if (StringUtils.isBlank(content)) return content;

        return URL_PATTERN.matcher(content).replaceAll(match -> {
            String url = match.group();
            return "<a href=\"" + url + "\" target=\"_blank\" style=\"text-decoration: none; color: #0066cc;\">" + url + "</a>";

        });
    }

    /**
     * 提取消息中的图片链接
     */
    public static List<String> extractImageUrls(String content) {
        List<String> images = new ArrayList<>();
        if (StringUtils.isBlank(content)) return images;

        Matcher matcher = IMAGE_PATTERN.matcher(content);
        while (matcher.find()) {
            images.add(matcher.group(1)); // 去除URL参数
        }
        return images;
    }

    /**
     * 转换图片链接为缩略图标签
     */
    public static String convertImagesToThumbnails(String content) {
        if (StringUtils.isBlank(content)) return content;

        return IMAGE_PATTERN.matcher(content).replaceAll(match -> {
            String url = match.group(1);
            return "<img src=\"" + url + "\" class=\"msg-thumbnail\" style=\"max-width: 200px;\"/>";
        });
    }
    /**
     * 转义消息中的HTML标签（防XSS攻击）
     */
    public static String escapeHtml(String content) {
        return HtmlUtils.htmlEscape(content);
    }

}